import nodemailer from 'nodemailer';
import dotenv from 'dotenv';

dotenv.config();

// 创建邮件传输对象
const transporter = nodemailer.createTransport({
  host: process.env.MAIL_HOST,
  port: process.env.MAIL_PORT,
  secure: true,
  auth: {
    user: process.env.MAIL_USER,
    pass: process.env.MAIL_PASS
  },
  pool: true,
  maxConnections: 1,
  maxMessages: 50,
  socketTimeout: 60000,      // 增加到60秒
  connectionTimeout: 60000,  // 增加到60秒
  greetingTimeout: 60000,   // 增加到60秒
  logger: true,
  debug: true,
  tls: {
    rejectUnauthorized: false
  },
  // 添加重试配置
  retry: {
    retries: 3,
    factor: 2,
    minTimeout: 1000,
    maxTimeout: 3000
  }
});

// 创建带重试的连接函数
const retryConnection = async (retries = 3) => {
  for (let i = 0; i < retries; i++) {
    try {
      await transporter.verify();
      return true;
    } catch (error) {
      console.error(`连接尝试 ${i + 1} 失败:`, error);
      if (i === retries - 1) throw error;
      // 等待时间递增
      await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, i)));
    }
  }
  return false;
};

let isConnected = false;
const ensureConnection = async () => {
  if (!isConnected) {
    try {
      await retryConnection();
      isConnected = true;
      console.log('邮件服务器连接成功');
    } catch (error) {
      console.error('邮件服务器连接失败:', error);
      isConnected = false;
      throw error;
    }
  }
};

const testEmailConnection = async () => {
  try {
    await ensureConnection();
    return true;
  } catch (error) {
    console.error('邮件服务器配置错误:', error);
    return false;
  }
};

// 带重试的发送邮件函数
const sendMail = async (options, retries = 3) => {
  for (let i = 0; i < retries; i++) {
    try {
      await ensureConnection();

      const mailOptions = {
        from: {
          name: 'StoryPlush',
          address: process.env.MAIL_USER
        },
        headers: {
          'X-Priority': '1',
          'X-MSMail-Priority': 'High',
          'Importance': 'high',
          'Content-Type': 'text/html; charset=UTF-8'
        },
        ...options
      };

      const info = await transporter.sendMail(mailOptions);
      console.log('邮件发送成功:', info.messageId);
      return true;
    } catch (error) {
      console.error(`发送尝试 ${i + 1} 失败:`, error);
      
      if (error.code === 'ETIMEDOUT' || error.code === 'ECONNECTION') {
        isConnected = false;
      }

      if (i === retries - 1) throw error;
      
      // 等待时间递增
      await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, i)));
    }
  }
};

// 优雅关闭连接
const closeConnection = () => {
  if (isConnected) {
    transporter.close();
    isConnected = false;
    console.log('邮件服务器连接已关闭');
  }
};

process.on('SIGTERM', closeConnection);
process.on('SIGINT', closeConnection);

export { transporter, testEmailConnection, sendMail }; 